package net.phoenix.repository.property;

import javax.jcr.Item;
import javax.jcr.Node;
import javax.jcr.Property;
import javax.jcr.RepositoryException;
import javax.jcr.Value;
import javax.jcr.ValueFormatException;
import javax.jcr.nodetype.PropertyDefinition;

import net.phoenix.repository.BasicNode;

/**
 * 
 * Jigsaw server
 * 
 * @author <a href="shamphone@gmail.com">Li XiongFeng</a>
 * @date 2012-1-3
 * @version 1.0.0
 */
public class PathProperty extends BasicProperty {
	/**
	 * create single value property
	 * 
	 * @param node
	 * @param definition
	 * @param value
	 */
	public PathProperty(BasicNode node, PropertyDefinition definition, Value value) {
		super(node, definition, value);

	}

	/**
	 * create multiple values property
	 * 
	 * @param node
	 * @param definition
	 * @param values
	 */
	public PathProperty(BasicNode node, PropertyDefinition definition, Value[] values) {
		super(node, definition, values);
	}

	/**
	 * create a property with default value;
	 * 
	 * @param node
	 * @param definition
	 */
	public PathProperty(BasicNode node, PropertyDefinition definition) {
		super(node, definition);

	}
	
	/**
	 * 
	 * @return Content
	 * @throws RepositoryException
	 * @throws IllegalStateException
	 */
	@Override
	public Node getNode() throws IllegalStateException, RepositoryException {
		if (this.values.length == 0)
			return null;
		String path = this.getValue().getString();
		return this.node.getSession().getNode(path);
	}

	@Override
	public Property getProperty() throws ValueFormatException, IllegalStateException, RepositoryException {
		String path = this.getValue().getString();
		if (path == null)
			return null;
		Item item = this.getParent().getSession().getItem(path);
		if (item == null)
			return null;
		if (!item.isNode())
			return (Property) item;
		else
			throw new ValueFormatException("This is a node not property!");
	}
}
